// Example of keyboard and mouse event trapping in a 
//	win32 console app.
// ReadConsoleInputW waits for an event before proceding.
// PeekConsoleInput does not wait.
//
// by Brian Schick
// 1/5/10
//

#include <windows.h>
#include <conio.h>
#include <iostream>

#define INBUFSIZE 128

using namespace std;

int main()
{
	cout << "Hello world." << endl;

	bool running = true;
	COORD newmousecoord = {0,0}, oldmousecoord, cursorpos = {0,0};
	bool changedmousecoord = false;
	POINT mousepoint, wich = {0,0};
	HANDLE stdinh, stdouth;
	INPUT_RECORD ir[INBUFSIZE];
	DWORD irsread;


	// Initialize
	stdinh  = GetStdHandle( STD_INPUT_HANDLE );
	stdouth = GetStdHandle( STD_OUTPUT_HANDLE );

	SetConsoleMode( stdinh, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT );

	while( running )
	{
		irsread = 0;
		if ( 0 == PeekConsoleInput( stdinh, ir, INBUFSIZE, &irsread ) )
			cout << "Peek Error: " << GetLastError();
		// Keyboard Input
		//if ( kbhit() )
		if( irsread > 0 )
		{
			if ( 0 == ReadConsoleInput( stdinh, ir, INBUFSIZE, &irsread ) )
				cout << "Read Error: " << GetLastError();
			for( unsigned int i = 0; i < irsread; i++ )
			{
				switch( ir[i].EventType )
				{
				case KEY_EVENT:
					if ( ir[i].Event.KeyEvent.bKeyDown )
					{
						switch( ir[i].Event.KeyEvent.wVirtualKeyCode )
						{
						case 'Q':
							running = false;
							break;
						case VK_SPACE:
							break;
						}
					}
					break;

				case MOUSE_EVENT:
					if ( newmousecoord.X != ir[i].Event.MouseEvent.dwMousePosition.X 
						|| newmousecoord.Y != ir[i].Event.MouseEvent.dwMousePosition.Y )
					{
						changedmousecoord = true;
						oldmousecoord = newmousecoord;
						newmousecoord = ir[i].Event.MouseEvent.dwMousePosition;
					}
					break;
				}
			}
		}
		else
		{
		// Update
		// Draw
			GetCursorPos( &mousepoint ); // Absolute position.  Need Window position to get location of cursor.
			SetConsoleCursorPosition( stdouth, cursorpos );
			cout << "No" << endl << "X " << mousepoint.x << " Y " << mousepoint.y << "      " << endl 
				<< "X " << newmousecoord.X << " Y " << newmousecoord.Y << "            ";

			if ( changedmousecoord )
			{
			SetConsoleCursorPosition( stdouth, oldmousecoord );
			cout << " ";
			SetConsoleCursorPosition( stdouth, newmousecoord );
			cout << "@";
			}

		}
	}

	// End Draw
	SetConsoleCursorPosition( GetStdHandle( STD_OUTPUT_HANDLE ), cursorpos );
	cout << "Fin";

	return 0;
}